import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const bom = await db.bOM.findUnique({
      where: { id: params.id },
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        creator: {
          select: { id: true, name: true, username: true }
        },
        items: {
          include: {
            supplier: {
              select: { id: true, name: true, code: true }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        hardwareVersions: {
          select: { id: true, version: true, name: true }
        },
        requirements: {
          include: {
            creator: {
              select: { id: true, name: true, username: true }
            },
            assignee: {
              select: { id: true, name: true, username: true }
            }
          }
        }
      }
    })

    if (!bom) {
      return NextResponse.json(
        { error: 'BOM not found' },
        { status: 404 }
      )
    }

    return NextResponse.json(bom)
  } catch (error) {
    console.error('Error fetching BOM:', error)
    return NextResponse.json(
      { error: 'Failed to fetch BOM' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json()
    const {
      version,
      name,
      description,
      status,
      currency,
      totalCost
    } = body

    const bom = await db.bOM.update({
      where: { id: params.id },
      data: {
        ...(version && { version }),
        ...(name && { name }),
        ...(description !== undefined && { description }),
        ...(status && { status }),
        ...(currency && { currency }),
        ...(totalCost !== undefined && { totalCost })
      },
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        creator: {
          select: { id: true, name: true, username: true }
        }
      }
    })

    return NextResponse.json(bom)
  } catch (error) {
    console.error('Error updating BOM:', error)
    return NextResponse.json(
      { error: 'Failed to update BOM' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await db.bOM.delete({
      where: { id: params.id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting BOM:', error)
    return NextResponse.json(
      { error: 'Failed to delete BOM' },
      { status: 500 }
    )
  }
}